<template>
  <basic-container>
    <avue-crud
      :option="option"
      :search.sync="search"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      v-model="form"
      ref="crud"
      @row-save="rowSave"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @sort-change="sortChange"
      @on-load="onLoad"
    >
    <!-- :permission="permissionList" -->

      <template slot="menuLeft">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="small"
          @click.stop="clickAdd"
          >新 增</el-button
        >
        <!-- v-if="permissionList.addBtn" -->
        <div style="color: #E6A23C;padding:5px 0">
          开通收款单后，需要向支付公司申请配置授权目录：https://pay.ruishengyi.com/payment
        </div>
      </template>

      <template slot-scope="scope" slot="menu">
        <el-button
          size="small"
          type="text"
          @click.stop="rowDel(scope.row)"
          >删除</el-button
        >
        <el-button
          size="small"
          type="text"
          @click.stop="getPreview(scope.row)"
          >表单二维码</el-button
        >
        <el-button
          size="small"
          type="text"
          @click.stop="editTemplate(scope.row)"
          >内容设计</el-button
        >
        <el-button size="small" type="text" @click.stop="toGo(scope.row)"
          >缴费记录</el-button
        >
      </template>

      <!-- <template slot-scope="{}" slot="rpiNoSearch">
        <select-page
          ref="searchRpiSelect"
          label="rpiName"
          value="rpiNo"
          :select.sync="search.rpiNo"
          :url="website.searchLink.merchantUrl"
          placeholder-text="商户"
          filter-key="searchParam"
          @update:select="searchrpiNoChange"  @clear:select="searchrpiNoClear"
        ></select-page>
      </template> -->

      <template slot-scope="{}" slot="rpsNoSearch">
        <select-page
          ref="searchrpsSelect"
          label="rpsName"
          value="rpsNo"
          :select.sync="search.rpsNo"
          :url="website.searchLink.rpsUrl"
          placeholder-text="门店"
          filter-key="searchParam"
          :params="{
            rpiNo:rpiNo,
          }"
          @update:select="searchrpsNoChange" @clear:select="searchrpsNoClear"
        ></select-page>
      </template>

      <template slot-scope="{}" slot="rpstNoSearch">
        <select-page
          ref="searchrpstSelect"
          label="rpstName"
          value="rpstNo"
          :select.sync="search.rpstNo"
          :url="website.searchLink.rpstUrl"
          placeholder-text="操作员"
          filter-key="searchParam"
          :params="{
            rpiNo:rpiNo,
            rpsNo:search.rpsNo
          }"
        ></select-page>
      </template>

      <template slot-scope="{ row }" slot="formStatus">
        <el-switch
          :active-value="1"
          :inactive-value="0"
          active-text="启用"
          inactive-text="禁用"
          v-model="row.formStatus"
          @change="handleFormStatus(row)"
        >
        </el-switch>
      </template>
      
      <template slot-scope="{ disabled, size }" slot="createTimeBeginSearch">
        <el-date-picker
          v-model="search.createTimeBegin"
          type="date"
          value-format="yyyy-MM-dd"
          @change="createTimeBeginChange"
          placeholder="请输入创建开始时间"
        ></el-date-picker>
      </template>
      <template slot-scope="{ disabled, size }" slot="createTimeEndSearch">
        <el-date-picker
          v-model="search.createTimeEnd"
          type="date"
          value-format="yyyy-MM-dd"
          @change="createTimeEndChange"
          placeholder="请输入创建结束时间"
        ></el-date-picker>
      </template>
      <template slot-scope="{ disabled, size }" slot="beginDateSearch">
        <el-date-picker
          v-model="search.beginDate"
          type="date"
          value-format="yyyy-MM-dd"
          @change="beginDateChange"
          placeholder="请输入缴费单开始时间"
        ></el-date-picker>
      </template>
      <template slot-scope="{ disabled, size }" slot="endDateSearch">
        <el-date-picker
          v-model="search.endDate"
          type="date"
          value-format="yyyy-MM-dd"
          @change="endDateChange"
          placeholder="请输入缴费单结束时间"
        ></el-date-picker>
      </template>
    </avue-crud>

    <el-dialog
      title="新增"
      append-to-body
      :visible.sync="addVisible"
      v-if="addVisible"
      width="555px"
      :before-close="handleClose"
      @close="close"
    >
      <el-form
        :model="templateForm"
        :rules="templateRules"
        ref="templateForm"
        label-width="100px"
        class="demo-ruleForm"
        size="mini"
      >
        <!-- <el-form-item required label="商户:" prop="rpiNo">
          <select-page
            ref="searchRpiSelect"
            label="rpiName"
            value="rpiNo"
            :select.sync="templateForm.rpiNo"
            :url="website.searchLink.merchantUrl"
            placeholder-text="商户"
            filter-key="searchParam"
            @update:select="rpiNoChange" @clear:select="rpiNoClear"
          ></select-page>
        </el-form-item> -->
        <el-form-item label="门店:" prop="rpsNo">
          <select-page
            ref="rpsSelect"
            label="rpsName"
            value="rpsNo"
            :select.sync="templateForm.rpsNo"
            :url="website.searchLink.rpsUrl"
            placeholder-text="门店"
            filter-key="searchParam"
            :params="{
              rpiNo:templateForm.rpiNo
            }"
            @update:select="rpsNoChange" @clear:select="rpsNoClear"
          ></select-page>
        </el-form-item>

        <el-form-item label="操作员:" prop="rpstNo">
          <select-page
            ref="rpstSelect"
            label="rpstName"
            value="rpstNo"
            :select.sync="templateForm.rpstNo"
            :url="website.searchLink.rpstUrl"
            placeholder-text="操作员"
            :params="{
              rpiNo:templateForm.rpiNo,
              rpsNo:templateForm.rpsNo
            }"
            filter-key="searchParam"
          ></select-page>
        </el-form-item>

        <el-form-item required label="缴费名称:" prop="formName">
          <el-input v-model="templateForm.formName"></el-input>
        </el-form-item>

        <el-form-item label="缴费频次:" prop="frequency">
          <el-radio-group v-model="templateForm.frequency">
            <el-radio :label="0">单次</el-radio>
            <el-radio :label="1">不限次</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item required label="有效期:">
          </el-date-picker>
          <el-col :span="11">
          <el-form-item prop="beginDate">
            <el-date-picker type="date" placeholder="选择日期" v-model="templateForm.beginDate" style="width: 100%;" @blur="blurBegin"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col class="line" :span="2" style="text-align: center;">至</el-col>
        <el-col :span="11">
          <el-form-item prop="endDate">
            <el-date-picker type="date" placeholder="选择日期" v-model="templateForm.endDate" style="width: 100%;" @blur="blurEnd"></el-date-picker>
          </el-form-item>
        </el-col>
        </el-form-item>
        
        <el-form-item label="温馨提示:" class="tipsBox">
          <div>名称一经创建无法修改，请谨慎哦！</div>
        </el-form-item>

        <div class="flex">
          <el-button size="mini" type="primary" @click="submitForm('templateForm')" :disabled="disabledBtn">立即创建</el-button>
          <el-button size="mini" @click="resetForm('templateForm')">重置</el-button>
        </div>
      </el-form>
    </el-dialog>

    <el-image-viewer
      style="z-index: 99999 !important"
      v-if="imageIiew"
      :on-close="
        () => {
          imageIiew = false;
        }
      "
      :url-list="[rqUrlImage]"
    ></el-image-viewer>
  </basic-container>
</template>

<script>
import { getList,apiFormCode,add, remove,editStatus} from "@/api/rb-oem/feetMer/payment";
import { mapGetters } from "vuex";
import ElImageViewer from "element-ui/packages/image/src/image-viewer";
import selectPage from "@/components/select-page/select-page";

export default {
  components: {
    ElImageViewer,
    selectPage
  },
  data() {
    return {
      templateForm:{
        frequency:0,
        dateArr:[]
      },
      templateRules:{
        rpiNo: [
          {required: true, message: "请选择商户", trigger: ["change","blur"]}
        ],
        formName: [
          {required: true, message: "请输入缴费名称", trigger: ["change","blur"]}
        ],
        beginDate: [
          { type: 'date', required: true, message: '请选择开始日期', trigger: 'change' }
        ],
        endDate: [
          { type: 'date', required: true, message: '请选择结束日期', trigger: 'change' }
        ],
      },
      imageIiew: false,
      rqUrlImage: "",
      form: {},
      query: {},
      search: {},
      loading: true,
      addVisible: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      option: {
        // height: "auto",
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        viewBtn: false,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        selection: false,
        // searchMenuSpan: 6,
        searchLabelWidth: 120,
        columnBtn: false,
        searchIcon: true,
        searchIndex: 3,
        indexLabel: "序号",
        menuWidth:250,
        column: [
          {
            label: "商户编号",
            prop: "rpiNo",
            type: "input",
            searchLabel: "商户",
            // search: true,
            minWidth: 140,
            overHidden: true,
          },
          {
            label: "商户名称",
            prop: "rpiName",
            type: "input",
            minWidth: 180,
            overHidden: true,
          },
          {
            label: "门店编号",
            prop: "rpsNo",
            type: "input",
            searchLabel: "门店",
            search: true,
            minWidth: 140,
            overHidden: true,
          },
          {
            label: "门店名称",
            prop: "rpsName",
            type: "input",
            minWidth: 180,
            overHidden: true,
          },
          {
            label: "操作员编号",
            prop: "rpstNo",
            type: "input",
            searchLabel: "操作员",
            search: true,
            minWidth: 140,
            overHidden: true,
          },
          {
            label: "操作员名称",
            prop: "rpstName",
            type: "input",
            minWidth: 180,
            overHidden: true,
          },
          {
            label: "缴费频次",
            prop: "frequency",
            type: "input",
            hide: true,
            search: true,
            type: "select",
            // minWidth: 140,
            // overHidden:true,
            dicData: [
              {
                label: "单次",
                value: 0,
              },
              {
                label: "不限次",
                value: 1,
              },
            ]
          },
          {
            label: "缴费频次",
            prop: "frequencyName",
            type: "input",
            minWidth: 140,
            overHidden: true,
          },
          {
            label: "缴费单编号",
            prop: "formCode",
            type: "input",
            minWidth: 140,
            overHidden: true,
          },
          {
            label: "缴费单名称",
            prop: "formName",
            type: "input",
            search: true,
            minWidth: 140,
            overHidden: true,
          },
          {
            label: "缴费单状态",
            prop: "formStatus",
            type: "select",
            search: true,
            // dicData: [
            //   {
            //     label: "不可用",
            //     value: 0,
            //   },
            //   {
            //     label: "可用",
            //     value: 1,
            //   },
            // ],
            dicUrl: "/api/blade-system/dict/dictionary?code=is_on",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            minWidth:150
          },
          // {
          //   label: "缴费单状态",
          //   prop: "formStatusName",
          //   type: "input",
          //   minWidth: 110,
          //   overHidden: true,
          // },
          // {
          //   label: "缴费单二维码",
          //   prop: "qrCode",
          //   type: "input",
          // },
          {
            label: "创建日期",
            prop: "createTime",
            type: "input",
            minWidth: 140,
            overHidden: true,
          },
          {
            label: "创建开始日期",
            prop: "createTimeBegin",
            search: true,
            hide: true,
            display: false,
          },
          {
            label: "创建结束日期",
            prop: "createTimeEnd",
            search: true,
            hide: true,
            display: false,
          },
          {
            label: "缴费单开始时间",
            prop: "beginDate",
            type: "input",
            search: true,
            minWidth: 140,
            overHidden: true,
          },
          {
            label: "缴费单结束时间",
            prop: "endDate",
            type: "input",
            search: true,
            minWidth: 140,
            overHidden: true,
          },
        ],
      },
      data: [],
      disabledBtn:false
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    // permissionList() {
    //   return {
    //     addBtn: this.vaildData(this.permission.payment_add, false),
    //     viewBtn: this.vaildData(this.permission.payment_view, false),
    //     delBtn: this.vaildData(this.permission.payment_del, false),
    //   };
    // },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
  },
  created(){
    this.rpiNo = this.$route.query.rpiNo;
  },
  methods: {
    searchrpiNoChange(value){
      if (value) {
        this.search.rpsNo = "";
        this.search.rpstNo = "";

        let params = {
          rpiNo: value
        };
        this.$refs['searchrpsSelect'].getOptionList(params);
        this.$refs['searchrpstSelect'].getOptionList(params);
      }
    },
    searchrpiNoClear(){
      this.search.rpsNo = "";
      this.search.rpstNo = "";

      this.$refs['searchrpsSelect'].getOptionList();
      this.$refs['searchrpstSelect'].getOptionList();
    },
    searchrpsNoChange(value){
      if (value) {
        this.search.rpstNo = "";

        let params = {
          rpsNo: value,
          rpiNo:this.rpiNo
        };
        this.$refs['searchrpstSelect'].getOptionList(params);
      }
    },
    searchrpsNoClear(){
      this.search.rpstNo = "";

      this.$refs['searchrpstSelect'].getOptionList();
    },
    /** @func 有效期开始 */
    blurBegin(){
      if (this.templateForm.endDate) {
        if ( Date.parse(this.templateForm.beginDate) > Date.parse(this.templateForm.endDate) ) {
          this.$alert("有效期开始时间不能大于结束时间", "提示", {
            confirmButtonText: "确定",
            type: "warning",
          })
            .then(() => (this.templateForm.beginDate = ""))
            .catch(() => (this.templateForm.beginDate = ""));
        }
      }
    },
    /** @func 有效期结束 */
    blurEnd(){
      if (this.templateForm.beginDate) {
        if ( Date.parse(this.templateForm.endDate) < Date.parse(this.templateForm.beginDate) ) {
          this.$alert("有效期结束时间不能小于开始时间", "提示", {
            confirmButtonText: "确定",
            type: "warning",
          })
            .then(() => (this.templateForm.endDate = ""))
            .catch(() => (this.templateForm.endDate = ""));
        }
      }
    },
    /** @func 图片预览 */
    getPreview(item) {
      apiFormCode(item.formCode).then(res=>{
        this.rqUrlImage = res.data.data;
        this.imageIiew = true;
      })
    },
    /** @func 页面跳转 */
    toGo(row) {
      // if(type === 0){
      //   /**@func 内容设计 */
      // }else if(type === 1){
      //   /**@func 缴费机构 */
      // }

        /**@func 缴费记录 */
        this.$router.push({ name: '缴费记录',query: { formCode: row.formCode,rpiNo:row.rpiNo }})
    },
    /** @func 内容设计 */
    editTemplate(row){

      this.$router.push({ name: '内容设计',query: { formCode: row.formCode }})
    },
    rpiNoChange(value){
      if (value) {
        this.templateForm.rpsNo = "";
        this.templateForm.rpstNo = "";
        let params = {
          rpiNo: value
        };
        this.$refs['rpsSelect'].getOptionList(params);
        this.$refs['rpstSelect'].getOptionList(params);
      }
    },
    rpiNoClear(){
      this.templateForm.rpsNo = "";
      this.templateForm.rpstNo = "";
      
      this.$forceUpdate();

      this.$refs['rpsSelect'].getOptionList();
      this.$refs['rpstSelect'].getOptionList();
    },
    rpsNoChange(value){
      if (value) {
        this.templateForm.rpstNo = "";
        let params = {
          rpsNo: value,
          rpiNo:this.templateForm.rpiNo
        };
        this.$refs['rpstSelect'].getOptionList(params);
      }
    },
    rpsNoClear(){
      this.templateForm.rpstNo = "";
      this.$forceUpdate();

      this.$refs['rpstSelect'].getOptionList();
    },
    submitForm(formName) {
      let that = this;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          that.disabledBtn = true;
          add(that[formName]).then(() => {
            that.onLoad(that.page);
            that.$message({
              type: "success",
              message: "操作成功!",
            });
            that.$refs[formName].resetFields();
            that.addVisible = false;
            that.disabledBtn = false;

          }, (error) => {
              that.disabledBtn = false;
              loading();
              window.console.log(error);
            }
          );
        } else {
          return false;
        }
      });
    },
    resetForm(formName){
      this.disabledBtn = false;
      this.$nextTick(()=>{
        this.$refs[formName].resetFields();
      })
    },
    clickAdd(){
      this.addVisible = true;
      this.templateForm.rpiNo = this.$route.query.rpiNo;
    },
    handleClose(done) {
      this.templateForm={}
      done();
    },
    close(){
      this.templateForm={}
    },
    /** @func 缴费单状态开关 */
    handleFormStatus(row) {
      editStatus(row.formCode, row.formStatus,row.rpiNo).then(
        () => {},
        (error) => {
          row.formStatus = row.formStatus == 1 ? 0 : 1;
          window.console.log(error);
        }
      );
    },
    createTimeBeginChange() {
      if (this.search.createTimeEnd) {
        if (
          Date.parse(this.search.createTimeBegin) >
          Date.parse(this.search.createTimeEnd)
        ) {
          this.$alert("创建开始时间不能大于结束时间", "提示", {
            confirmButtonText: "确定",
            type: "warning",
          })
            .then(() => (this.search.createTimeBegin = ""))
            .catch(() => (this.search.createTimeBegin = ""));
        }
      }
    },
    createTimeEndChange() {
      if (this.search.createTimeBegin) {
        if (
          Date.parse(this.search.createTimeEnd) <
          Date.parse(this.search.createTimeBegin)
        ) {
          this.$alert("创建结束时间不能小于开始时间", "提示", {
            confirmButtonText: "确定",
            type: "warning",
          })
            .then(() => (this.search.createTimeEnd = ""))
            .catch(() => (this.search.createTimeEnd = ""));
        }
      }
    },

    beginDateChange() {
      if (this.search.endDate) {
        if (
          Date.parse(this.search.beginDate) > Date.parse(this.search.endDate)
        ) {
          this.$alert("缴费单开始时间不能大于结束时间", "提示", {
            confirmButtonText: "确定",
            type: "warning",
          })
            .then(() => (this.search.beginDate = ""))
            .catch(() => (this.search.beginDate = ""));
        }
      }
    },
    endDateChange() {
      if (this.search.beginDate) {
        if (
          Date.parse(this.search.endDate) < Date.parse(this.search.beginDate)
        ) {
          this.$alert("缴费单结束时间不能小于开始时间", "提示", {
            confirmButtonText: "确定",
            type: "warning",
          })
            .then(() => (this.search.endDate = ""))
            .catch(() => (this.search.endDate = ""));
        }
      }
    },
    rowSave(row, done, loading) {
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowDel(row) {
      let that = this;
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(row.formCode,row.rpiNo)

        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.$refs.crud.toggleSelection();
        });
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query,{rpiNo:this.rpiNo})
      ).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.$emit('total', this.page.total);
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    sortChange(val) {
      if (val.order == "ascending") {
        //正序
        this.query.ascs = val.prop;
        this.query.descs = "";
      } else {
        //倒序
        this.query.descs = val.prop;
        this.query.ascs = "";
      }
      this.refreshChange();
    },
  },
};
</script>

<style lang="scss" scoped>
/deep/ .el-select{
  width: 100% !important;
}
.flex{
  display: flex;
  justify-content: center;
}

.tipsBox{
  color: #E6A23C;
  .tipsBox, /deep/ .el-form-item__label{
    color: #E6A23C !important;
  }
}
</style>
